package com.atguigu.tran;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.StringUtils;

/**
 * @author yhm
 * @create 2024-04-02 10:17
 */
public class Test04_MapAndFilter {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        DataStreamSource<String> lineDs = env.socketTextStream("hadoop102", 7777);

        // 3. 处理数据
        // 传入的数据是  sensor_1,1000,10
        // 并且里面还有脏数据
        // 需求:将接收到的字符串转换为javaBean

        // (1) 先过滤
        SingleOutputStreamOperator<String> filterStream = lineDs.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                // 为空删除
                if (StringUtils.isNullOrWhitespaceOnly(value)) {
                    return false;
                }
                String[] words = value.split(",");
                boolean flag = false;
                try {
                    if (words.length == 3) {
                        WaterSensor waterSensor = new WaterSensor(words[0], Long.valueOf(words[1]), Integer.valueOf(words[2]));
                        flag = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return flag;
            }
        });

        SingleOutputStreamOperator<WaterSensor> beanStream = filterStream.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] words = value.split(",");
                return new WaterSensor(words[0], Long.valueOf(words[1]), Integer.valueOf(words[2]));
            }
        });

        // 4. 输出
        beanStream.print();

        // 5. 执行环境
        env.execute();
    }
}
